package com.hertz.iris.view.alarm;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.github.kevinsawicki.wishlist.SingleTypeAdapter;
import com.hertz.iris.Injector;
import com.hertz.iris.IrisApplication;
import com.hertz.iris.R;
import com.hertz.iris.R.layout;
import com.hertz.iris.core.NormalAlarmService;
import com.hertz.iris.pojo.NormalAlarm;
import com.hertz.iris.pojo.Ring;
import com.hertz.iris.ui.ItemListFragment;
import com.hertz.iris.ui.TextDrawable;
import com.hertz.iris.ui.ThrowableLoader;
import com.hertz.iris.util.BundleKeys;
import com.hertz.iris.util.Constants;
import com.hertz.iris.util.Ln;
import com.hertz.iris.util.Strings;

public class RingSelectorFrag extends ItemListFragment<Ring>{

	private MediaPlayer mMediaPlayer;
	private TextDrawable textDrawable;
	private OnRingSelectorListener myCallback;
	private int lastClickItemPosition;
	private View lastClickItemPositionView;
	private byte volume = Constants.DEFAULT_VALUME;
	@Inject protected NormalAlarmService normalAlarmService;
	
	public interface OnRingSelectorListener{
		public void ringSelectorListener(byte index,String title,String uri);
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		initPauseTextDrawable(activity);
		myCallback = (OnRingSelectorListener)activity;
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		Bundle ars = getArguments();
        NormalAlarm na = (NormalAlarm)ars.getSerializable(BundleKeys.NormalAlarmBundleKeys.NORMAL_ALARM_KEY);
		volume = na.getVolume();			
        return inflater.inflate(layout.ring_selector_frag, null);
    }

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		setEmptyText(R.string.no_ring);
		
//		Bundle ars = getArguments();
//        NormalAlarm na = (NormalAlarm)ars.getSerializable(BundleKeys.NormalAlarmBundleKeys.NORMAL_ALARM_KEY);
//		Adapter adapter = getListView().getAdapter();
//		for(int i = 0; i < adapter.getCount(); i++){
//			Ring ring = (Ring)adapter.getItem(i);
//			if(ring.getName().equals(na.getRingName())){
//				getListView().setItemChecked(i, true);
//			}
//		}
	}

	@Override
    protected void configureList(Activity activity, ListView listView) {
        super.configureList(activity, listView);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listView.setFastScrollEnabled(true);
        listView.setDividerHeight(0);
        
    }
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Injector.inject(this);
    }
	
	@Override
    public void onDestroyView() {
        setListAdapter(null);
        super.onDestroyView();
    }
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Uri uri = null;
		Ring ring = (Ring)l.getItemAtPosition(position);
		if(ring != null && !Strings.isBlank(ring.getName()))
				uri = Uri.parse(ring.getUri());
		else
			return;
		
		myCallback.ringSelectorListener(Integer.valueOf(position).byteValue(),ring.getName(), uri == null ? "" : uri.toString());
		Drawable bg = v.getBackground();
		if(bg == null ){
			setItemBackground(v, textDrawable);
			stopRingtone();
			
			if(uri != null){
				playRingtone(uri);
			}
		}else{
			setItemBackground(v, null);
			stopRingtone();
		}
		if(lastClickItemPosition != position){
			setItemBackground(lastClickItemPositionView, null);
		}
		lastClickItemPosition = position;
		lastClickItemPositionView = v;
	}

	
	
//	@Override
//	public void onHiddenChanged(boolean hidden) {
//		super.onHiddenChanged(hidden);
//		if(hidden){
//			stopRingtone();
//		}
//	}
//	
	

	@Override
	public void onStop() {
		super.onStop();
		stopRingtone();
	}

	private void playRingtone(Uri uri) {
	    stopRingtone();
	    mMediaPlayer = new MediaPlayer();
	    try {
	      mMediaPlayer.setDataSource(uri.toString());
	      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
	      mMediaPlayer.setVolume((float)volume/100, (float)volume/100);
	      mMediaPlayer.prepare();
	      mMediaPlayer.start();
	    } catch (IOException e) {
	      Ln.w("TonePicker", "Unable to play track: "+uri != null ? uri.toString() : "null");
	      e.printStackTrace();
	    }
	  }

	  private void stopRingtone() {
	    if (mMediaPlayer != null) {
	      mMediaPlayer.stop();
	      mMediaPlayer.release();
	      mMediaPlayer = null;
	    }
	  }
	  
	private void initPauseTextDrawable(Context context) {
		textDrawable = new TextDrawable(context);
		String pause = getResources().getString(R.string.icon_playing);
		textDrawable.setText(pause);
		textDrawable.setTextAlign(Layout.Alignment.ALIGN_CENTER);
		textDrawable.setTypeface(IrisApplication.getInstance().getTypeface());
		textDrawable.setTextColor(0xb02ecc71);
		textDrawable.setTextSize(8);
	}
	private void setItemBackground(View v,Drawable bg){
		int sdk = android.os.Build.VERSION.SDK_INT;
		if(v != null){
			if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
			    v.setBackgroundDrawable(bg);
			} else {
			    v.setBackground(bg);
			}
		}
	}

	@Override
    public Loader<List<Ring>> onCreateLoader(int id, Bundle args) {
        final List<Ring> initialItems = items;
        return new ThrowableLoader<List<Ring>>(getActivity(), items) {

            @Override
            public List<Ring> loadData() throws Exception {
                try {
                    if(getActivity() != null) {
                        return normalAlarmService.getSysRings();
                    } else {
                        return Collections.emptyList();
                    }

                } catch (android.os.OperationCanceledException e) {
                    Activity activity = getActivity();
                    if (activity != null)
                        activity.finish();
                    return initialItems;
                }
            }
        };
    }

	
	
	@Override
	public void onLoadFinished(Loader<List<Ring>> loader, List<Ring> items) {
		super.onLoadFinished(loader, items);
		Bundle ars = getArguments();
        NormalAlarm na = (NormalAlarm)ars.getSerializable(BundleKeys.NormalAlarmBundleKeys.NORMAL_ALARM_KEY);
        SingleTypeAdapter<Ring> adapter = getListAdapter().getWrappedAdapter();
		for(int i = 0; i < adapter.getCount(); i++){
			Ring ring = (Ring)adapter.getItem(i);
			if(ring.getName().equals(na.getRingName())){
				getListView().setItemChecked(i, true);
			}
		}
	}

	@Override
    protected int getErrorMessage(Exception exception) {
        return R.string.error_loading_ring;
    }

	@Override
    protected SingleTypeAdapter<Ring> createAdapter(List<Ring> items) {
        return new RingListAdapter(getActivity().getLayoutInflater(), items);
    }
	
}
